<template>
  <div>
    
    <Panel title="费率组时段表" useBack :intro="intro">
     
    <div slot="body" class="time-input">
       <el-button  type="primary" @click="addIds()" style="margin-left:10px;margin-bottom:20px" title="在下面加一行费率组分段">加一行</el-button>
        <el-button v-if="gid"  @click="copy()" style="margin-left:10px;margin-bottom:20px">复制数据</el-button>
        <el-button   @click="past()" style="margin-left:10px;margin-bottom:20px">粘贴</el-button>
        <div style="padding: 10px;color: #0072ff;">费率名称：{{name}}</div>
        <div class="" style="margin: 20px 0;display: flex;align-items: center;">
          <div>批量填入：</div>
          <div class="input-box">
                 <span class="input-title">平台:</span>
                 <el-select v-model="thirdId" placeholder="平台">
                   <el-option
                    v-for="item in thirdList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
            </div>
            <div class="input-box">
                 <span class="input-title">峰:</span>
                 <el-input v-model="feng" placeholder="电费"></el-input>
            </div>
            <div class="input-box">
                 <span class="input-title">平:</span>
                 <el-input v-model="ping" placeholder="电费"></el-input>
            </div>
            <div class="input-box">
                 <span class="input-title">谷:</span>
                 <el-input v-model="gu" placeholder="电费"></el-input>
            </div>
            <div class="input-box">
                 <span class="input-title">推送服务费:</span>
                 <el-input v-model="tuiService" placeholder="服务费"></el-input>
            </div>
            <div class="input-box">
                 <span class="input-title">结算服务费:</span>
                 <el-input v-model="jieService" placeholder="服务费"></el-input>
            </div>
            <el-button type="danger"  @click="computePrice()" style="margin-left:10px">计算</el-button>
        </div>
      <el-form :inline="true" class="demo-form-inline" id="formData">
        <div class="text-box" v-for="(item, index) of formSku.foodSkuSpeciftcations" :key="index">
           <el-row :gutter="10" >
              <el-col :span="24" style="display:flex">
                <div class="input-box1">
                  <span class="input-title">时间段:</span><el-input v-model="item.beginTime" placeholder="开始时间"></el-input>-
                  <el-input v-model="item.endTime" placeholder="结束时间"></el-input>
               </div>
                <!-- <el-input v-model="time" placeholder="时间段"></el-input> -->
               <div class="input-box">
                  <span class="input-title">阶段:</span><el-input v-model="item.name" placeholder="时间段名称"></el-input>
               </div>
               <div class="input-box">
                 <span class="input-title">电费:</span>
                 <el-input v-model="item.electric" placeholder="电费"></el-input>
               </div>
               <div class="input-box">
                 <span class="input-title">服务费:</span>
                 <el-input v-model="item.service" placeholder="服务费"></el-input>
               </div>
                <div class="input-box">
                 <span class="input-title">折扣:</span>
                 <el-input v-model="item.discount" placeholder="服务费折扣"></el-input>
               </div>
               <div class="input-box">
                 <span class="input-title">电费溢价:</span>
                 <el-input v-model="item.powerPremium" placeholder="电费"></el-input>
               </div>
               <div class="input-box">
                 <span class="input-title">服务费溢价:</span>
                 <el-input v-model="item.servicePremium" placeholder="服务费"></el-input>
               </div>
                <div class="input-box">
                 <span class="input-title">状态:</span>
                  <el-select v-model="item.state" placeholder="状态">
                   <el-option
                    v-for="item in stateList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
               </div>
               <div class="input-box">
                 <span class="input-title">类型:</span>
                 <el-select v-model="item.type" placeholder="类型">
                   <el-option
                    v-for="item in typeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
               </div>
                
               
                
                 <el-button  type="primary"  @click="deleteIds(index)" style="margin-left:10px">-</el-button>
              </el-col>
            </el-row>
        </div>
        <!-- <div>备注：第一条默认从00:00:00开始，只需选择结束时间。 最后一条默认截止时间23:59:59，只需选择最后一条的开始时间</div> -->

           <el-button style="margin-left:40%" type="primary" @click="submit" >保存</el-button>
      </el-form>
    </div>
   
    </Panel>

  </div>
</template>
<script>
import request from "@/tools/request";
import Panel from "@/components/Panel";
import TableEncapsulation from "@/components/TableEncapsulation";
import TablePager from "@/components/Pager";
import SearchInput from "@/components/SearchInput";
import ModalPanel from "@/components/ModalPanel";
export default {
  name: "time",
  components: {
    TableEncapsulation,
    TablePager,
    Panel,
    SearchInput,
    ModalPanel
  },
  data() {
    return {
      intro:{
        title: '',
        content: `批量填入数据时，峰平谷价格必填；当推送服务费和结算服务费未填入时，代表不修改费率服务费。推送服务费和结算服务费必须同时存在；推送服务费将填入下面的费率分段服务费。服务费溢价（快电、新电途）=-(推送服务费-结算服务费)；服务费溢价（星络充）=-(电费+结算服务费)*0.031+(推送服务费-结算服务费)`
      },
      time:'',
      beginTime:'',
      endTime:'',
      thirdId: '',
      feng: '',
      ping: '',
      gu: '',
      tuiService: '',
      jieService: '',
      typeList:[
        {value: 1,label: '谷'},
        {value: 2,label: '峰'},
        {value: 3,label: '平'},
        {value: 4,label: '尖'}
      ],
      thirdList: [
        {value: '',label: '请选择平台'},
        {value: 1,label: '快电'},
        {value: 2,label: '新电途'},
        {value: 3,label: '星络充'},
      ],
       stateList:[
        {value: 1,label: '正常'},
        {value: 0,label: '停用'},
      ],
      dataItem:{'beginTime':'','endTime':'','electric':'','servicePremium':'','powerPremium':'','name':'','service':'','discount':'','state':'','type':'','times':new Date(2016, 9, 0, 0, 0),'rang':{selectableRange: '00:00:00 - 23:59:59'}},
      timeData:[
        {'beginTime':'','endTime':'','electric':'','servicePremium':'','powerPremium':'','name':'阶段一','service':'','discount':'','state':'','type':'','times':new Date(2016, 9, 0, 0, 0),'rang':{selectableRange: '00:00:00 - 23:59:59'}}
        ],
      visible:false,
      modalData:{},
      tableData: [],
      gid:'',
       pager: {
        use: true,
        total: 0,
        current: 1,
        size: 10,
        showTotal: true
      },
      name: '',
      operation: true,
      state: '',
    
      total: 1,
      maxseconed:86400,
      formSku: {
        foodSkuSpeciftcations: [],
      },
    };
  },
   watch: {
    'formSku.foodSkuSpeciftcations':{
      handler: function () {
      },
      deep: true,
    },
  },
  created() {
    if(this.$route.query.id){
      this.gid = this.$route.query.id
    }
    this.name = this.$route.query.name
    this.getRate();
  },
  computed: {
    tableConfig () {
      return {
        selection: true,
        columnConfig: [
          {
            label: "编号",
            type: "text",
            prop: "id",
            align: "center"
          },
          {
            label: "名称",
            type: "text",
            prop: "name",
            align: "center"
          },
          {
            label: "备注",
            type: "text",
            prop: "mark",
            align: "center"
          },
          {
            label: "状态",
            type: "other",
            prop: "state",
            align: "center",
            fnc: val => val==1? '启用' : '停用'
          },
          {
            label: "更新时间",
            type: "text",
            prop: "updateTime",
            align: "center"
          },
          this.operation && {
            type: "operation",
            align: "center",
            label: "操作",
            width:180
          }
        ].filter(Boolean)
        }
    }
  },
  methods: {
    computePrice(){
      let gu = parseFloat(this.gu), ping = parseFloat(this.ping), feng = parseFloat(this.feng), jieService =this.jieService? parseFloat(this.jieService): 0, tuiService =this.tuiService? parseFloat(this.tuiService):0, thirdId = this.thirdId
      if(!thirdId || !feng || !ping || !gu ){
        this.$message.error('请完善计算前的所有空格')
        return
      }
      let guOutPrice = 0, pingOutPrice = 0, fengOutPrice = 0
      if(thirdId =='3'){
        //星络充
        guOutPrice = -((gu + jieService)*0.031 + (tuiService - jieService)).toFixed(3)
        pingOutPrice = -((ping + jieService)*0.031 + (tuiService - jieService)).toFixed(3)
        fengOutPrice = -((feng + jieService)*0.031 + (tuiService - jieService)).toFixed(3)
      }else{
        //快电，新电途
        var pti = -(tuiService - jieService).toFixed(3)
        guOutPrice = pti
        pingOutPrice = pti
        fengOutPrice = pti
      }
      let data = this.formSku.foodSkuSpeciftcations
      let this_ = this
      data.map((item, index) => {
        if(!item.type){
          this_.$message.error('类型不能为空')
          return false
        }
        item.electric = item.type == 1 ? gu: item.type == 3 ? ping : feng
        item.service = tuiService
        if(jieService&& tuiService){
          item.servicePremium = item.type == 1 ? guOutPrice: item.type == 3 ? pingOutPrice : fengOutPrice
        }
        
        return item
      })
      this.formSku.foodSkuSpeciftcations = data
    },

    async getRate() {
      const res = await request({
        url: "/rate/group/time/list/"+ this.$route.query.id,
        method: "GET",
        data: {}
      });
      let date = new Date()
      let year = date.getFullYear()
      let month = date.getMonth()
      let day = date.getDate()
      // res.list.map( item => {
      //   var begin = item.beginTime.split(":")
      //   item.beginTime = new Date(year, month, day, parseInt(begin[0]), parseInt(begin[1]), parseInt(begin[2]))
      //   var end = item.endTime.split(":")
      //   item.endTime = new Date(year, month, day, parseInt(end[0]), parseInt(end[1]), parseInt(end[2]))
      //   item.times = [item.beginTime, item.endTime]
      //   return  item
      // })

      this.formSku.foodSkuSpeciftcations = res.list
      // this.tableData = res.page.list
      // this.pager.total = res.page.totalCount
      // this.pager.current = res.page.currPage
    },
    async submit() {
      let data = this.formSku.foodSkuSpeciftcations
      if (!data) return this.$message.error('至少包含一条数据')
      data.map((item, index) => {
        if(!item.beginTime || !item.endTime) return this.$message.error('请完善时间段')
        return item
      })
      let res = await request({
      url: '/rate/group/time/add/batch',
      method: 'POST',
      data: {groupId:this.$route.query.id, list:data}
      })
      if (res.code !==0) return
      this.$message.success('提交成功')
      this.$router.go(-1)
    },
    pageChange(val) {
      this.pager.current = val;
      this.getRate();
    },
    copy(){
      this.$store.commit('copyTimeDate', this.formSku.foodSkuSpeciftcations)
      this.$message.success('复制成功')
    },
    past(){
      let timeData = this.$store.getters.timeData
      this.formSku.foodSkuSpeciftcations = timeData
    },
    edit(rowData){
      this.modalData = {...rowData}
      this.visible = true
    },
    changeSearch(key, val) {
      this[key] = val;
      this.query.page = 1;
    },
    editStore(id){
      this.$router.push({ path: "/grate/group/info",query:{id:id} })
    },
    commentDetail(id){
      this.$router.push({ path: "/storeDetail",query:{id:id,type: "toview"} })
    },
    remove(id){
       this.$confirm('确认删除吗', '操作确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then( async () => {
        await DELETE(`/store/${id}`,id)
        this.$message.success('删除成功')
        if(this.tableData.length===1 && this.pager.current>1)
          this.$set(this.pager,'current', this.pager.current-1)
        this.queryData()
      })
    },
    addIds(){
      this.formSku.foodSkuSpeciftcations.push({})
    },
    deleteIds(index) {
      this.formSku.foodSkuSpeciftcations.splice(index, 1)
    }
  }
}
</script>
<style lang='scss' scope>
.noshow{
  display: none;
}
.input-title{
  font-size: 14px;
    color: #636363;
    display: flex;
    align-items: center;
}
.el-date-editor.el-range-editor.el-input__inner.el-date-editor--timerange{
  width: 201px;
}
.input-box {
    margin-left: 2px;
    display: flex;
    align-items: center;
}
.input-box1 {
  display: flex;
  align-items: center;
}

.text-box {
  .el-input {
    width: 80px;
  }
  .el-row {
    margin-bottom: 10px;
  }
}
.examine{
    display: flex;
    align-items: center;
    :global{
        div{
            color: #fff;
            padding: 10px;
            margin: 0 10px;
            border-radius: 2px;
            font-size: 14px;
            cursor: pointer;
            min-width: 60px;
            text-align: center;
        }
        .adopt{
                background: #409EFF;
        }
    }
}
.search_box {
  display: flex;
  align-items: center;
  flex-wrap: wrap;

  :global {
    .el-input {
      width: 150px;
    }
    .el-select {
      .el-input {
        width: 90px;
      }
    }
    .el-input__icon {
      line-height: 27px;
    }
    .el-range-separator{
      line-height: 26px;
    }
  }
}

.topSelect {
  background-color: white;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}
.time-input {
  .el-input.el-input--suffix{
    width: 80px;
  }
  .el-input {
    width: 100px;
    max-width: 140px;
  }
}
</style>